package filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class userLoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession(false);

        // 记录用户之前访问的页面
        String originalURL = ((HttpServletRequest) request).getRequestURI();
        session.setAttribute("redirectAfterLogin", originalURL);

        // 获取 session 中的用户信息
        Integer userIdInt = (Integer) session.getAttribute("userId");
        String userId = userIdInt != null ? userIdInt.toString() : "未知";
        String userType= (String) session.getAttribute("userType");

        if (userId == null || (!userType.equals("user"))) {
            // 设置响应类型和编码格式，然后返回一个简单的提示页面
            res.setContentType("text/html;charset=UTF-8");
            res.getWriter().write(
                    "<html>" +
                            "<head><title>无权限访问</title></head>" +
                            "<body>" +
                            "<h1>抱歉，您没有权限访问此页面！</h1>" +
                            "<p>请使用管理员账号登录后再访问。</p>" +
                            "</body>" +
                            "</html>"
            );
            return;
        } else {
            chain.doFilter(request, response);
        }
    }
}
